//
//  HomeViewController.swift
//  Exam-iOS
//
//  Created by 李胜锋 on 2018/1/29.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import UIKit
import SnapKit

class HomeViewController: ViewController, Refreshable {

    
    var data:Home.HomeIndex?
    var typeModules = [String]()   //类型模块列表
    var pageNum = 2
    
    var collectionView:UICollectionView!
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        setPopRecognizerEnable(true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        typeModules = ["错题", "收藏", "记录"]

        title = "首页"
        let leftBarItem = UIBarButtonItem.init(title: "我的", style: .plain, target: self, action: #selector(HomeViewController.leftClick))
        navigationItem.leftBarButtonItem = leftBarItem

        let layout = UICollectionViewFlowLayout.init()
        collectionView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        
        collectionView.backgroundColor = UIColor.white
        
        collectionView.register(HomeModuleCell.classForCoder(), forCellWithReuseIdentifier:HomeModuleCell.identifier())
        collectionView.register(HomeExamInfoCell.classForCoder(), forCellWithReuseIdentifier:HomeExamInfoCell.identifier())
        collectionView.register(HomeNewsCell.classForCoder(), forCellWithReuseIdentifier: HomeNewsCell.identifier())
        collectionView.register(HomeNewsHeaderView.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: HomeNewsHeaderView.identifier())
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (maker) in
            maker.edges.equalTo(safeAreaInsets())
        }
        
        initRefresh(collectionView, headerBlock: { [weak self] in
            self?.loadIndexData()
        }) { [weak self] in
            self?.loadNews()
        }
        
        ///监听考试等级变化
        NotificationCenter.default.addObserver(forName: NSNotification.Name.init(AccountLevelIdChangedNotification), object: nil, queue: nil) { [weak self] (notification) in
            self?.collectionView.mj_header.beginRefreshing()
        }
        
        collectionView.mj_header.beginRefreshing()
    }
    
    func loadIndexData() {
        let levelId = AccountStorage.default.account.levelId
        Home.getIndex(levelId:levelId, success: { [weak self] (homeIndex) in
            
            guard let strongSelf = self else { return }
            strongSelf.data = homeIndex
            
            strongSelf.collectionView.reloadData()
            strongSelf.endRefreshing()
            self?.pageNum = 2
        })  { [weak self]  (code, msg) in
            self?.collectionView.mj_header.endRefreshing()
        }
        
    }
    
    func loadNews() {
        shurenProvider.rx.request(.newsList(pageNum: self.pageNum)).asObservable().mapRespnseJson().subscribe(onNext: { [weak self] (data) in
            guard let list = data as? [[String: Any]] else { return }
            if list.count > 0 {
                self?.pageNum += 1
                self?.data?.news?.append(contentsOf: list)
                self?.collectionView.reloadData()
            }
        }, onError: {[weak self] (error) in
            self?.collectionView.mj_footer.endRefreshing()
            showError(error)
        }, onCompleted: { [weak self] in
            self?.collectionView.mj_footer.endRefreshing()
        }).disposed(by: disposeBag)
    }
    
    
    
    @objc func leftClick() {
        sideslipOpenLeftMenu()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension HomeViewController: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 4
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        var count = 0
        guard let data = data else { return count }
        switch section {
        case 0:
            count = data.entrances?.count ?? 0
            
        case 1:
            count = typeModules.count
            
        case 2:
            if data.examTime != nil {
                count = 1
            }
        default:
            count = data.news?.count ?? 0
        }
        return count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        switch indexPath.section {
            //真题、章节、模拟
        case 0:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeModuleCell.identifier(), for: indexPath) as! HomeModuleCell
            if let entrances = data?.entrances {
                if indexPath.item < entrances.count {
                    let module = entrances[indexPath.item]
                    let title = module["title"] as? String
                    let id = module["classId"] as? Int
                    cell.set(title: title, index: indexPath.item)
                }
            }
            
            return cell
        
            //错题、章节、记录
        case 1:
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeModuleCell.identifier(), for: indexPath) as! HomeModuleCell
        
            if indexPath.item < typeModules.count {
                let title = typeModules[indexPath.item]
                
                cell.set(title: title)
            }
            return cell
            
        case 2:
            
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeExamInfoCell.identifier(), for: indexPath) as! HomeExamInfoCell
            if let examTime = data?.examTime {
                let title = examTime["countDown"] as? String
                let subTitle = examTime["summary"] as? String
                cell.set(title: title, subTitle: subTitle)
            }
            
            return cell
            
        default:
            
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomeNewsCell.identifier(), for: indexPath) as! HomeNewsCell
            
            if let news = data?.news {
                if indexPath.item < news.count {
                    let module = news[indexPath.item]
                    let title = module["title"] as? String
                    let poster = module["poster"] as? String
                    cell.set(title: title, imageUrl: poster)
                }
            }
            return cell
        }
    
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        if indexPath.section == 3,  kind == UICollectionElementKindSectionHeader, data?.news != nil {

            let reusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: HomeNewsHeaderView.identifier(), for: indexPath) as! HomeNewsHeaderView

            return reusableView
        }

        return UICollectionReusableView()
    }
}

extension HomeViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        switch indexPath.section {
        //真题、章节、模拟
        case 0:
            if let entrances = data?.entrances {
                if indexPath.item < entrances.count {
                    let module = entrances[indexPath.item]
                    guard let title = module["title"] as? String else { return }
                    guard let id = module["classId"] as? Int  else { return }
                    let vc = PaperListViewController.init((title, id))
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }
           
            //错题、章节、记录
        case 1:
            ///判断用户是否登录
            if AccountStorage.default.isLogin() == false {
                showLogin(controller: self, dismissHandle: { [weak self] (result) in
                    if result {
                        guard let strongSelf = self else { return }
                        strongSelf.collectionView(strongSelf.collectionView, didSelectItemAt: indexPath)
                        return
                    }
                })
                
                return
            }
            
            if indexPath.item == 0 {
                //错题
                let errorVC = PaperErrorsViewController()
                navigationController?.pushViewController(errorVC, animated: true)
            }
            else if indexPath.item == 1 {
                //收藏
                let collectVC = CollectionViewController()
                navigationController?.pushViewController(collectVC, animated: true)
            }
                ///记录
            else if indexPath.item == 2 {
                let vc = PaperRecordViewController()
                navigationController?.pushViewController(vc, animated: true)
            }
            break
            
            
            //新闻头条
        case 3:
            guard let newsList = self.data?.news else { return }
            if indexPath.item < newsList.count {
                let news = newsList[indexPath.item]
                guard let id = news["id"] as? Int else { return }
                let newsDetailVC = NewsDetailViewController.init(id)
                navigationController?.pushViewController(newsDetailVC, animated: true)
                
            }
            break
            
        default:
           break
        }
    }
}

extension HomeViewController: UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        
        var spacing:CGFloat = 20
        
        if section == 3 {
            spacing = 0
        }
        
        return spacing
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        var insets = UIEdgeInsets.zero
        
        switch section {
        case 0:
            insets = UIEdgeInsetsMake(18.5, 17.5, 0, 17.5)
            
        case 1:
            insets = UIEdgeInsetsMake(20, 17.5, 0, 17.5)
            
        case 2:
            insets = UIEdgeInsetsMake(20, 17.5, 20, 17.5)
        default:
            
            insets = UIEdgeInsetsMake(0, 0, 20, 0)
        }
        return insets
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        var width:CGFloat = 0
        var height:CGFloat = 0
        
        guard let data = data else {
            return CGSize.zero
        }
        
        switch indexPath.section {
        case 0:
            var col:CGFloat = 0
            let moduleCount = data.entrances?.count ?? 0
            if  moduleCount == 1 {
                col = 1
            }
            else if moduleCount == 2 || data.entrances?.count == 4 {
                col = 2
            }
            else {
                col = 3
            }
            
            width = (collectionView.lsf_width - 17.5 * 2 - (col - 1) * 20.0) / col
            height = (collectionView.lsf_width - 17.5 * 2 - (3 - 1) * 20.0) / 3
            
        case 1:
            width = (collectionView.lsf_width - 17.5 * 2 - (3 - 1) * 20.0) / 3
            height = 43.0
            
        case 2:
            width = collectionView.lsf_width - 2 * 17.5
            height = 70.0
        default:
            width = collectionView.lsf_width
            height = 88.0
        }
        
        let size = CGSize.init(width: width, height: height)
        return size
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        var size = CGSize.zero
        
        if  section == 3, data?.news != nil {
            size = CGSize.init(width: collectionView.lsf_width, height: 34)
        }
        
        return size
    }
}

